package smartbooksdb.util;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;

public class SendMail extends Thread implements CommonConstantsDB {

	Map<String, String> mail = null;

	@Override
	public void run() {
		MimeMessage message = new MimeMessage(getSession(mail));
		Multipart multipart = new MimeMultipart();

		try {
			message.setFrom(new InternetAddress(mail.get(MAIL_FROM), mail
					.get(MAIL_DISPLAY_NAME)));
			message.addRecipient(RecipientType.TO,
					new InternetAddress(mail.get(MAIL_TO1)));
			message.addRecipient(RecipientType.TO,
					new InternetAddress(mail.get(MAIL_TO2)));
			message.setSubject(mail.get(MAIL_SUBJECT));
			MimeBodyPart messageBodyPart = new MimeBodyPart();
			messageBodyPart.setText(mail.get(MAIL_BODY));
			multipart.addBodyPart(messageBodyPart);
			message.setContent(multipart);
			Transport.send(message);
		} catch (MessagingException e) {
			ErrorLogger.log(e, false);
		} catch (UnsupportedEncodingException e) {
			ErrorLogger.log(e, false);
		}

	}

	public void send(Map<String, String> mail) {
		this.mail = mail;
		start();
	}

	private Session getSession(Map<String, String> mail) {
		Authenticator authenticator = new Authenticator(mail);

		Properties properties = new Properties();
		properties.setProperty("mail.smtp.submitter", authenticator
				.getPasswordAuthentication().getUserName());
		properties.setProperty("mail.smtp.auth", "true");

		properties.setProperty("mail.smtp.host", mail.get(MAIL_HOST));
		properties.setProperty("mail.smtp.port", mail.get(MAIL_PORT));

		return Session.getInstance(properties, authenticator);
	}

	private class Authenticator extends javax.mail.Authenticator {

		private PasswordAuthentication authentication;

		public Authenticator(Map<String, String> mail) {
			authentication = new PasswordAuthentication(
					mail.get(MAIL_USERNAME), mail.get(MAIL_PASSWORD));
		}

		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return authentication;
		}
	}
}